/**************************************************************
 *
 * Copyright (c) 2008, ******, All Rights Reserved.
 *
 * 名 称:
 *		util.cpp
 * 位 置:
 *		src/pub/util.cpp
 * 描 述:
 *		公用实用类
 * 备 注:
 *		无
 * 修 改:
 *		2008-09-14  Simon   - 创建
 *
 **************************************************************/

extern "C"
{
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
}
#include "pub/def.h"
#include "pub/str.h"
#include "pub/err.h"
#include "pub/util.h"

using namespace std;

//----------------------------------------------
//	获取系统时间
//----------------------------------------------
void sysdt(String& sdate, String& stime)
{
	time_t now;
	struct tm *localnow;
	char buff[8 + 1];

	try
	{
		time(&now);
		localnow = localtime(&now);

		memset(buff, 0x00, sizeof(buff));
		sprintf(buff, "%04d%02d%02d", localnow->tm_year + 1900, localnow->tm_mon + 1, localnow->tm_mday);
		sdate.assign(buff, strlen(buff));

		memset(buff, 0x00, sizeof(buff));
		sprintf(buff, "%02d%02d%02d", localnow->tm_hour, localnow->tm_min, localnow->tm_sec);
		stime.assign(buff, strlen(buff));
	}
	catch (...)
	{
		throw Error(ERRCODE_APP, "获取系统时间失败");
	}
}

//----------------------------------------------
//	获取网络接口
//----------------------------------------------
void netif(String& ip, String& mac)
{
	int sock;
	struct ifreq ifr;
	struct arpreq arp;
	char buff[32];

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock == -1)
		throw Error(ERRCODE_APP, "获取网络接口失败");

	strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
	ifr.ifr_name[IFNAMSIZ - 1] = 0;

	if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
		throw Error(ERRCODE_APP, "获取网络接口失败");

	sprintf(buff, inet_ntoa(((struct sockaddr_in*) (&ifr.ifr_addr))->sin_addr));
	ip.assign(buff, strlen(buff));

	arp.arp_pa.sa_family = AF_INET;
	arp.arp_ha.sa_family = AF_INET;
	if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
		throw Error(ERRCODE_APP, "获取网络接口失败");

	sprintf(buff, "%02X-%02X-%02X-%02X-%02X-%02X", (unsigned char) ifr.ifr_hwaddr.sa_data[0], (unsigned char) ifr.ifr_hwaddr.sa_data[1], (unsigned char) ifr.ifr_hwaddr.sa_data[2], (unsigned char) ifr.ifr_hwaddr.sa_data[3], (unsigned char) ifr.ifr_hwaddr.sa_data[4], (unsigned char) ifr.ifr_hwaddr.sa_data[5]);
	mac.assign(buff, strlen(buff));
}

